首页 > 试题广场 >

识别有效的IP地址和掩码并进行分类统计

[编程题]识别有效的IP地址和掩码并进行分类统计
  • 热度指数:329088 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

请解析IP地址和对应的掩码,进行分类识别。要求按照A/B/C/D/E类地址归类,不合法的地址和掩码单独归类。

所有的IP地址划分为 A,B,C,D,E五类

A类地址从1.0.0.0到126.255.255.255;

B类地址从128.0.0.0到191.255.255.255;

C类地址从192.0.0.0到223.255.255.255;

D类地址从224.0.0.0239.255.255.255;

E类地址从240.0.0.0255.255.255.255


私网IP范围是:

从10.0.0.0到10.255.255.255

从172.16.0.0到172.31.255.255

从192.168.0.0到192.168.255.255


子网掩码为二进制下前面是连续的1,然后全是0。(例如:255.255.255.32就是一个非法的掩码)
(注意二进制下全是1或者全是0均为非法子网掩码)

注意:
1. 类似于【0.*.*.*】和【127.*.*.*】的IP地址不属于上述输入的任意一类,也不属于不合法ip地址,计数时请忽略
2. 私有IP地址和A,B,C,D,E类地址是不冲突的



输入描述:

多行字符串。每行一个IP地址和掩码,用~隔开。

请参考帖子https://www.nowcoder.com/discuss/276处理循环输入的问题。


输出描述:

统计A、B、C、D、E、错误IP地址或错误掩码、私有IP的个数,之间以空格隔开。

示例1

输入

10.70.44.68~255.254.255.0
1.0.0.1~255.0.0.0
192.168.0.2~255.255.255.0
19..0.~255.255.255.0

输出

1 0 1 0 0 2 1

说明

10.70.44.68~255.254.255.0的子网掩码非法,19..0.~255.255.255.0的IP地址非法,所以错误IP地址或错误掩码的计数为2;
1.0.0.1~255.0.0.0是无误的A类地址;
192.168.0.2~255.255.255.0是无误的C类地址且是私有IP;
所以最终的结果为1 0 1 0 0 2 1        
示例2

输入

0.201.56.50~255.255.111.255
127.201.56.50~255.255.111.255

输出

0 0 0 0 0 0 0

说明

类似于【0.*.*.*】和【127.*.*.*】的IP地址不属于上述输入的任意一类,也不属于不合法ip地址,计数时请忽略         
纯粹的业务题,要看清题目的要求,我卡了老半天
编辑于 2024-04-01 17:40:31 回复(0)
做了一晚上,我真废材啊
import sys

A, B, C, D, E, X, Y = 0, 0, 0, 0, 0, 0, 0

# 判断是否是数字字符串的序列
def not_all_int(string_list):
    for s in string_list:
        try:
            int(s)  # 尝试将字符串转换为整数
        except:
            return True  # 如果转换失败,则返回true并跳出函数
    return False  # 如果所有字符串都能成功转换为整数,则返回false

# 字符串的序列转化为int的序列
def list_str_to_int(string_list):  # 字符串转化成int
    int_list = list(map(int, string_list))
    return int_list

# 把整数序列转化为大长的二进制数表示,注意到前面多了个0b1 但是空位是全的。
def list_int_to_big_bin(int_list):
    int_numb = (
        int_list[0] * (2 ** 24)
        + int_list[1] * (2 ** 16)
        + int_list[2] * (2 ** 8)
        + int_list[3]
        + 2 ** 32
    )
    bin_numb = bin(int_numb)
    return bin_numb

# 判断子网掩码是否错误,错误则返回True
def sub_mask_false(bin_numb):
    str_numb = str(bin_numb)

    if str_numb == "0b1" + "0000" * 8 or str_numb == "0b1" + "1111" * 8:
        return True
    else:
        for i in range(len(str_numb) - 1):
            if str_numb[i] == "0" and str_numb[i + 1] == "1":
                return True
        return False

# 判断是否是私网,如果是,返回True
def private_net_ip(string_list):
    int_list = list_str_to_int(string_list)
    if int_list[0] == 10:
        return True
    elif int_list[0] == 172 and int_list[1] >= 16 and int_list[1] <= 31:
        return True
    elif int_list[0] == 192 and int_list[1] == 168:
        return True
    else:
        return False

# 判断ip地址是否在正确区间
# 如果第一个1或者127说明不合法,返回True,合法则返回False
def ip_address_false(string_list):
    ip_int_list = list_str_to_int(string_list)
    if ip_int_list[0] == 0 or ip_int_list[0] == 127:
        return True
    else:
        return False

# 正文
for line in sys.stdin:
    # 切割开~,分成两半
    str_0 = line.split("~")
    # 如果不足2个,就直接跳出去
    if len(str_0) < 2:
        break
    # 分别拿出来,切去换行符\n
    str_IP_Address_0 = str_0[0]
    str_subnet_mask_0 = str_0[1].replace("\n", "")
    # 切割开. 形成字符串的序列,这样的['10','20','15','40']
    str_IP_Address = str_IP_Address_0.split(".")
    str_subnet_mask = str_subnet_mask_0.split(".")

    # 判断是不是数字组成的字符串
    if not_all_int(str_IP_Address) or not_all_int(str_subnet_mask):
        X += 1
        continue

    # 判断IP地址是不是0或者127开头,如果是,直接舍去,不计数
    if ip_address_false(str_IP_Address):
        continue

    # 把子网掩码字符串变成整数,再拼成长的二进制数
    bin_numb = list_int_to_big_bin(list_str_to_int(str_subnet_mask))
    # 判断这个子网掩码是否合法
    if sub_mask_false(bin_numb):
        X += 1
        continue

    # 判断一个合法的ip地址,属于ABCDE
    int_list = list_str_to_int(str_IP_Address)
    if int_list[0] >= 1 and int_list[0] <= 126:
        A += 1  # A
    elif int_list[0] >= 128 and int_list[0] <= 191:
        B += 1  # B
    elif int_list[0] >= 192 and int_list[0] <= 223:
        C += 1  # C
    elif int_list[0] >= 224 and int_list[0] <= 239:
        D += 1  # D
    elif int_list[0] >= 240 and int_list[0] <= 255:
        E += 1  # E

    # 判断是否是私网
    if private_net_ip(str_IP_Address):
        Y += 1

print(A, B, C, D, E, X, Y)


发表于 2024-03-30 01:36:41 回复(0)
import sys
address = []
mask = []
A = 0
B = 0
C = 0
D = 0
E = 0
error = 0
private = 0
for line in sys.stdin:
    a = line.split("~")
    address.append(a[0])
    mask.append(a[1][:-1])

# 判断掩码是否合法
def is_valid_mask(m):
    x = ["255","254","252","248","240","224","192", "128","0"]

    m1 = m.split(".")
    n = 0
    sum1 = 0 # 四个码的和
    for code in m1:
        sum1 += int(code)
        if n == 1 and code != "0":
            return False 
        if code != "255":
            if code in x:
                n = 1
            else:
                return False
    if sum1 == 0&nbs***bsp;sum1 == 255 * 4:
        return False
    return True

# 判断IP地址是否合法
def is_valid_address(a):
    try:
        result = False
        for i in a.split("."):
            if int(i)>=0 and int(i)<=255:
                result = True
        return result
    except:
        return False

# 判断IP地址是否为私有IP
def is_private_IP(ip):
    a = ip.split(".")
    if a[0] == "10":
        return True
    if a[0] == "172":
        if int(a[1]) >= 16 and int(a[1]) <= 31:
            return True
    if a[0] == "192":
        if int(a[1]) == 168:
            return True
    return False


for i in range(len(address)):
    a = address[i].split(".")
    if a[0] == "0"&nbs***bsp;a[0] == "127":
        continue
    if is_valid_address(address[i]):        
        
        if is_valid_mask(mask[i]):
            # a = address[i].split(".")
            if int(a[0]) >= 1 and int(a[0]) <= 126:
                A += 1
            if int(a[0]) >= 128 and int(a[0]) <= 191:
                B += 1
            if int(a[0]) >= 192 and int(a[0]) <= 223:
                C += 1
            if int(a[0]) >= 224 and int(a[0]) <= 239:
                D += 1
            if int(a[0]) >= 240 and int(a[0]) <= 255:
                E += 1
            if is_private_IP(address[i]):
                private += 1 
        else:
            error += 1
            
    else:
        error += 1
    
print(A,B,C,D,E,error,private)

发表于 2024-02-28 02:44:02 回复(0)
第6组测试用例,子网掩码数据:
预期不应该是14组错误吗?官方预期是13组

提取出的错误掩码如下:
['255', '110', '255', '255']
1111111111011101111111111111111
['255', '255', '58', '255']
111111111111111111101011111111
['255', '255', '154', '0']
1111111111111111100110100
['255', '255', '255', '100']
1111111111111111111111111100100
['255', '255', '111', '255']
1111111111111111110111111111111
['255', '86', '0', '0']
11111111101011000
['255', '255', '255', '139']
11111111111111111111111110001011
['255', '255', '90', '255']
1111111111111111101101011111111
['255', '153', '0', '0']
111111111001100100
['255', '255', '255', '255']
11111111111111111111111111111111
['255', '0', '15', '0']
11111111011110
['255', '255   ', '255', '255']
11111111111111111111111111111111
['255', '0', '0', '226']
111111110011100010
['255', '255', '74', '255']
1111111111111111100101011111111

测试用例原数据如下:
25.240.129.203~255.110.255.255
183.181.49.4~255.0.0.0
172.177.113.45~255.0.0.0
176.134.46.246~255.0.0.0
153.63.21.56~255.255.58.255
23.135.167.228~255.0.0.0
204.58.47.149~255.0.0.0
113.33.181.46~255.255.255.0
73.245.52.119~255.255.154.0
23.214.47.71~255.0.0.0
139.124.188.91~255.255.255.100
142.94.192.197~255.0.0.0
53.173.252.202~255.0.0.0
127.201.56.50~255.255.111.255
118.251.84.111~255.0.0.0
130.27.73.170~255.0.0.0
253.237.54.56~255.86.0.0
64.189.222.111~255.255.255.139
148.77.44.147~255.0.0.0
59.213.5.253~255.255.0.0
3.52.119.131~255.255.0.0
213.208.164.145~255.255.0.0
24.22.21.206~255.255.90.255
89.43.34.31~255.0.0.0
9.64.214.75~255.0.0.0
110.156.20.173~255.153.0.0
71.183.242.53~255.255.0.0
119.152.129.100~255.0.0.0
38.187.119.201~255.0.0.0
73.81.221.180~255.255.255.255
73.198.13.199~255.0.15.0
99.42.142.145~255.255.255.0
196.121.115.160~255.0.0.0
226.30.29.206~255.0.0.0
244.248.31.171~255.255.255.255
59.116.159.246~255.0.0.0
121.124.37.157~255.0.0.226
103.42.94.71~255.255.0.0
125.88.217.249~255.255.74.255
73.44.250.101~255.255.255.0
发表于 2023-09-08 21:30:00 回复(0)
import sys

count = [0]*7
n = sys.stdin.readlines()

def IPclassify(IP_class, count, mask_correct):
    while mask_correct == 1:
        if IP_class[0] !='127' and IP_class[0] !='0':
            if IP_class[0] =='' or IP_class[1] =='' or IP_class[2] =='' or IP_class[3] =='':
                count[5] += 1
            elif (int(IP_class[0]) in range(1,127)) and (int(IP_class[1]) in range(0,256))\
            and (int(IP_class[2]) in range(0,256)) and (int(IP_class[3]) in range(0,256)):
                if int(IP_class[0]) == 10:
                    count[6] += 1
                count[0] += 1
            elif  (int(IP_class[0]) in range(128,192)) and (int(IP_class[1]) in range(0,256))\
            and (int(IP_class[2]) in range(0,256)) and (int(IP_class[3]) in range(0,256)):
                if (int(IP_class[0]) == 172) and (int(IP_class[1]) in range(16,32)):
                    count[6] += 1
                count[1] += 1
            elif  (int(IP_class[0]) in range(192,224)) and (int(IP_class[1]) in range(0,256))\
            and (int(IP_class[2]) in range(0,256)) and (int(IP_class[3]) in range(0,256)):
                if (int(IP_class[0]) == 192) and (int(IP_class[1]) == 168):
                    count[6] += 1
                count[2] += 1
            elif  (int(IP_class[0]) in range(224,240)) and (int(IP_class[1]) in range(0,256))\
            and (int(IP_class[2]) in range(0,256)) and (int(IP_class[3]) in range(0,256)):  
                count[3] += 1
            elif  (int(IP_class[0]) in range(240,256)) and (int(IP_class[1]) in range(0,256))\
            and (int(IP_class[2]) in range(0,256)) and (int(IP_class[3]) in range(0,256)):  
                count[4] += 1
        else:
            pass
        break
    return count

def maskclassify(IP_class,tolbase_str,count,mask_correct):
    if IP_class[0] !='127' and IP_class[0] !='0':
        if ('01' in tolbase_str) or ('1' not in tolbase_str) or ('0' not in tolbase_str):
            count[5] += 1
            mask_correct = 0
            return mask_correct,count
        else:
            mask_correct = 1
            return mask_correct,count
    else:
        mask_correct = 1
        return mask_correct,count

 
def baseconvert(mask_class):
    tolbase = []
    for i in range(len(mask_class)):
        twobase = []
        num = int(mask_class[i])
        if num == 0:
            tolbase.append('00000000')
        else :
            while num > 0:
                twobase.append(str(num%2))
                num = num // 2
            twobase_rev = ''.join(twobase[::-1])
            if len(twobase_rev) < 8:
                twobase_rev = twobase_rev.zfill(8)
            tolbase.append(twobase_rev)
    tolbase_str = ''.join(tolbase)
    return tolbase_str

for i in range(len(n)):
   
    IP = n[i].strip().split('~')[0]
    mask = n[i].strip().split('~')[1]
    IP_class = IP.split('.')
    mask_class = mask.split('.')
    tolbase_str = baseconvert(mask_class)
    #print(tolbase_str)
    mask_correct, count = maskclassify(IP_class, tolbase_str, count, mask_correct=1)
    #print(mask_correct)
    count = IPclassify(IP_class, count, mask_correct)

[print(item, end=' ') for item in count]



   
发表于 2023-09-05 18:01:54 回复(0)
import sys


def judge_ip(ip_list:list[str])->bool:
    flag = False
    if len(ip_list) == 4:
        if ip_list[0] in [str(i) for i in range(1,256)] and ip_list[0] != "127":
            for i in range(1,4):
                if ip_list[i] in [str(i) for i in range(256)]:
                    flag = True
    return flag


def get_ip_class(ip_list:list[str])->str:
    type = ""
    if ip_list[0] in [str(i) for i in range(1,127)]:
        type = "A"
    if ip_list[0] in [str(i) for i in range(128,192)]:
        type = "B"
    if ip_list[0] in [str(i) for i in range(192,224)]:
        type = "C"
    if ip_list[0] in [str(i) for i in range(224,240)]:
        type = "D"
    if ip_list[0] in [str(i) for i in range(240,256)]:
        type = "E"
    return type


def judge_personal_ip(ip_list:list[str])->bool:
    flag = False
    if ip_list[0] == "10":
        flag = True
    elif ip_list[0] == "172" and ip_list[1] in [str(i) for i in range(16,32)]:
        flag = True
    elif ip_list[0] == "192" and ip_list[1] == "168":
        flag = True
    return flag


def judge_mask(mask_list:list[str])->bool:
    flag = False
    sum_temp = 0
    legal_num = []
    for i in range(7,-1,-1):
        sum_temp += pow(2,i)
        legal_num.append(str(sum_temp))

    if len(mask_list) == 4:
        if mask_list[0] in legal_num and mask_list[1]=="0" and mask_list[2]=="0" and mask_list[3]=="0":
            flag = True
        if mask_list[0]=="255" and mask_list[1] in legal_num and mask_list[2]=="0" and mask_list[3]=="0":
            flag = True
        if mask_list[0]=="255" and mask_list[1]=="255" and mask_list[2] in legal_num and mask_list[3]=="0":
            flag = True
        if mask_list[0]=="255" and mask_list[1]=="255" and mask_list[2]=="255" and mask_list[3] in legal_num:
            flag = True
        
        if mask_list[0]=="255" and mask_list[1]=="255" and mask_list[2]=="255" and mask_list[3]=="255":
            flag = False
        if mask_list[0]=="0" and mask_list[1]=="0" and mask_list[2]=="0" and mask_list[3]=="0":
            flag = False
    
    return flag


A,B,C,D,E,wrong,personal = 0,0,0,0,0,0,0
for line in sys.stdin:
    # print(line)
    line = line.rstrip('\n')
    ip,mask = line.split('~')
    ip_list = [i for i in ip.strip(".").split(".") if i != ""]
    mask_list = [i for i in mask.strip(".").split(".") if i != ""]
    # print(ip_list)
    # print(mask_list)
    if ip_list[0] in ["0", "127"]:
        continue
    else:
        if judge_ip(ip_list) and judge_mask(mask_list):
            if judge_personal_ip(ip_list):
                personal += 1
            class_ = get_ip_class(ip_list)
            if class_ == "A":
                A += 1
            if class_ == "B":
                B += 1
            if class_ == "C":
                C += 1
            if class_ == "D":
                D += 1
            if class_ == "E":
                E += 1
        else:
            wrong += 1
print("{} {} {} {} {} {} {}".format(A,B,C,D,E,wrong,personal))


# 重点1:
# 使用 for line in sys.stdin 读进来的line会包括最后一个回车字符'\n',进行后续计算之前一定要记得先使用rstrip('\n')方法去掉
# 重点2:
# 对于ip = "19..0." 这种特殊字符串,单纯使用ip.split('.')得到的ip_list = ['19', '', '0', ''] 会包含空字符串,
# 如果不想包含空字符串,,需要使用ip_list = [part for part in ip.split('.') if part != ''],结果ip_list = ['19', '0']



发表于 2023-08-04 02:00:06 回复(0)
有无大佬帮我看看哪里错了,有一组用例不知道为什么有两个错误ip算a类和d类里去了
import sys 
a,b,c,d,e,err,pri = 0,0,0,0,0,0,0
ipt = []
for line in sys.stdin:
    temp = line.split()[0]
    ipt.append(temp)

for row in ipt:
    ips = row.split('~')[0].split('.')
    ym = row.split('~')[1].split('.') 
    if ips[0]=='0'&nbs***bsp;ips[0]=='127' : continue
    legal = True
    
    for i in ips:
        if not str(i).isdigit():
            legal = False
            break
        if not 0<=int(i)<=255:
            legal = False
            break
    yms = ''

    for j in ym:
        yms += str(bin(int(j)))
    yms = yms.replace('0b','')

    if ('10' not in yms)&nbs***bsp;('01' in yms):
        legal = False
    
    if not legal:
        err += 1
        continue

    if 1<=int(ips[0])<=127: a += 1
    if 128<=int(ips[0])<=191: b += 1
    if 192<=int(ips[0])<=223: c += 1
    if 224<=int(ips[0])<=239: d += 1
    if 240<=int(ips[0])<=255: e += 1
    if int(ips[0])==10: pri += 1
    if int(ips[0])==172 and 16<=int(ips[1])<=31: pri += 1
    if int(ips[0])==192 and int(ips[1])==168: pri += 1
print(a,b,c,d,e,err,pri)


发表于 2023-07-18 15:10:18 回复(0)
# 当ip为0或127开头,则即使子网掩码是错误的,也忽略不计数
import sys

input1 = [i.strip() for i in sys.stdin]

def isR(item,type):
    tmpData = item.split('.')
    if len(tmpData) != 4:
        return False
    else:
        if type=='ip':
            res = []
            for i in tmpData:
                if i =='':
                    res.append(False)
                elif 0<=int(i)<=255: 
                    res.append(True)
                else:
                    res.append(False)
            res = False if False in res else True
            return res
        elif type=='subCode':
            subCode_bin = get_ip_bin(item)
            if '1' not in subCode_bin:
                return False
            elif '0' not in subCode_bin:
                return False
            else:
                if subCode_bin.count('10')==1:
                    a,b = subCode_bin.split('10')
                    if '0' not in a and '1' not in b:
                        return True
                    else:
                        return False
                else:
                    return False
def get_ip_bin(item):
    res = [bin(int(i))[2:] for i in item.split('.')]
    for i in range(4):
        res[i] = '0'*(8-len(res[i]))+res[i]
    return ''.join(res)
def isIn(ipStart,ipEnd,res_ip):
    if int(get_ip_bin(ipStart)) <= int(res_ip) <= int(get_ip_bin(ipEnd)):
        return True
    else:
        return False
countRes = {'A':0,'B':0,'C':0,'D':0,'E':0,'***t_ip':0,'private':0}
for i in range(len(input1)):
    ip,subCode = input1[i].split('~')
    tmp = ip.split('.')
    if tmp[0]=='0'&nbs***bsp;tmp[0]=='127':
        continue
    if isR(ip,'ip') and isR(subCode,'subCode'):
        ip_bin = get_ip_bin(ip)
        subCode_bin = get_ip_bin(subCode)
        res_ip=''
        for j in range(32):
            if ip_bin[j] == '1' and subCode_bin[j] == '1':
                res_ip+='1'
            else:
                res_ip+='0'
        if isIn('1.0.0.0','126.255.255.255',res_ip):
            countRes['A']+=1
        elif isIn('128.0.0.0','191.255.255.255',res_ip):
            countRes['B']+=1
        elif isIn('192.0.0.0','223.255.255.255',res_ip):
            countRes['C']+=1
        elif isIn('224.0.0.0','239.255.255.255',res_ip):
            countRes['D']+=1    
        elif isIn('240.0.0.0','255.255.255.255',res_ip):
            countRes['E']+=1
        if isIn('10.0.0.0','10.255.255.255',res_ip)&nbs***bsp;isIn('172.16.0.0','172.31.255.255',res_ip)&nbs***bsp;isIn('192.168.0.0','192.168.255.255',res_ip):
            countRes['private']+=1
    else:
        countRes['***t_ip']+=1
print(*countRes.values(),sep=' ')

发表于 2023-07-06 15:09:06 回复(0)
ls = [str(i) for i in range(256)]
A = B = C = D = E = I = P = 0

def legal(b):
    n = 0
    a = "".join([bin(int(i))[2:].rjust(8, "0") for i in b])
    for i in range(1, len(a)):
        if a[i] != a[i - 1]:
            n += 1
    if n == 1:
        return True
    return False

while True:
    try:
        s = input().split("~")
        ip, yanma = s[0].split("."), s[1].split(".")
        if int(ip[0]) in (0, 127):
            pass
        elif sum([1 for i in ip+yanma if i in ls])==8 and legal(yanma):
            if 240 <= int(ip[0]) < 256:
                E += 1
            elif 224 <= int(ip[0]):
                D += 1
            elif 192 <= int(ip[0]):
                C += 1
            elif 128 <= int(ip[0]):
                B += 1
            elif 1 <= int(ip[0]):
                A += 1
            a=[int(i) for i in ip]
            if a[0]==10&nbs***bsp;(a[0]==172 and 16<=a[1]<=31)&nbs***bsp;(a[0]==192 and a[1]==168):
                P += 1
        else:
            I += 1
    except:
        break
print(A, B, C, D, E, I, P)

发表于 2023-06-02 17:39:03 回复(0)
有没有一种可能答案错了
发表于 2023-05-28 21:09:20 回复(0)
这题算垃圾不?我执行了n遍最后才发现,重复的掩码或者ip错误算1个,题目中压根没这样说,而且ip和掩码同时错,也没说算几个,如此描述不清楚,让人怎么写
发表于 2023-05-25 22:08:12 回复(0)
# 问题1,子网掩码中1均是连续的,不知如何入手(查看他人代码),使用s.rfind()和s.find()=>字符串方法不熟练
# 问题2:私有ip也可以是ABCDE类ip
# 问题3,子网掩码数字转为二进制后,1位删除0b,2则未根据实际补充8位数
# 问题4,使用list,导致index引用时错位;最好使用dict避免该问题
# 问题5:先判断ip和子网掩码有误,而忽略了子网掩码错误但ip不计数的情况(花费时间最长)
# 汇总:花费不少于2小时,一是python基础弱,二则逻辑思维不缜密
发表于 2023-05-16 17:39:02 回复(1)
import sys


def checkMask(mask):
    if mask[0] == "255":
        if mask[1] == mask[2] == "255":
            if mask[3] == "0":
                # 255.255.255.0
                return False
            else:
                #255.255.255.*
                return True
        elif mask[1] in "255":
            if mask[2] == mask[3] == "0":
                # 255.255.0.0
                return False
            else:
                #255.255.*
                return True
        elif mask[1] == mask[2] == mask[3] == '0':
            # 255.0.0.0
            return False
        else:
            #255.*
            return True
    else:
        #*.*
        return True


def checkIp(ip):
    if len(ip) != 4:
        return True
    for i in ip:
        # 非法ip
        if i == "":
            return True
        elif int(i) < 0&nbs***bsp;int(i) > 255:
            return True
    else:
        return False


A, B, C, D, E, err, pri = 0, 0, 0, 0, 0, 0, 0
# 获取每行字符串
for ip in sys.stdin:
    a = ip.split("~")
    ip = a[0].split(".")
    mask = a[1].strip().split(".")
    # 去除0和120
    if ip[0] in ("0", "127"):
        continue
    # 检测掩码
    if checkIp(mask):
        err += 1
        continue
    if checkMask(mask):
        err += 1
        continue
    # 检测IP段
    if checkIp(ip):
        err += 1
        continue
    # ip分类
    x, y = int(ip[0]), int(ip[1])
    if 1 <= x <= 126:
        A += 1
        if x == 10:
            pri += 1
    elif 128 <= x <= 191:
        B += 1
        if x == 172 and 16 <= y <= 31:
            pri += 1
    elif 192 <= x <= 223:
        C += 1
        if x == 192 and y == 168:
            pri += 1
    elif 224 <= x <= 239:
        D += 1
    elif 240 <= x <= 255:
        E += 1

print("{} {} {} {} {} {} {}".format(A, B, C, D, E, err, pri))

发表于 2023-03-24 01:34:35 回复(1)
第八组用例过不去,不是0,127 ip的问题,供参考。
第八组预期答案:71 41 21 12 10 68 1
第八组实际输出:70 41 21 12 10 69 1
代码如下:
# 数据输入
ip_mask = []
while 1:
    try:
        ip_mask.append(input())
    except:
        break
a=b=c=d=e=err=private=0
# 开始分类判断
for it in ip_mask:
    ip, mask = it.split('~')
    ip_list = []
    # 处理ip中有空
    for it in ip.split('.'):
        if it == '':
            ip_list.append(-1)
        else:
            ip_list.append(int(it))
    # 判断ip长度是否正确
    if len(ip_list) != 4:
        err += 1
        continue
    ip1, ip2, ip3, ip4 = ip_list
    # 忽略 0 127 开头 ip
    if ip1 == 0&nbs***bsp;ip1 == 127:
        continue
    else:
        # 判断子网掩码是否正确
        if mask not in ['255.0.0.0','255.255.0.0','255.255.255.0']:
            err += 1
            continue
        # 判断 ip 是否正确
        elif 0<= ip1 <=255 and 0<= ip2 <=255 and 0<= ip3 <=255 and 0<= ip4 <=255:
            # A类地址判断
            if 0<= ip1 <=126:
                a += 1
                if ip1 == 10:
                    private += 1
            # B类地址判断
            elif 128<= ip1 <=191:
                b += 1
                if ip1 ==172 and 16<= ip2 <= 31:
                    private += 1
            # c类地址判断
            elif 192<= ip1 <=223:
                c += 1
                if ip1 == 192 and ip2 == 168:
                    private += 1
            # D类地址判断
            elif 224 <= ip1 <=239:
                d += 1
            # E类地址判断
            else:
                e += 1
        # 错误ip计数
        else:
            err += 1

print(a,b,c,d,e,err,private)



发表于 2023-03-17 16:58:31 回复(0)

问题信息

难度:
75条回答 90976浏览

热门推荐

通过挑战的用户

查看代码